package cn.xx.user.service.impl;

import cn.xx.basic.constant.PetHomeConstant;
import cn.xx.basic.exception.CustomException;
import cn.xx.basic.util.AjaxResult;
import cn.xx.basic.util.MD5Utils;
import cn.xx.basic.util.StrUtils;
import cn.xx.user.domain.LoginInfo;
import cn.xx.user.mapper.LoginInfoMapper;
import cn.xx.user.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl implements ILoginInfoService {

    @Autowired
    LoginInfoMapper loginInfoMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public AjaxResult checkLogin(LoginInfo loginInfo) throws CustomException {
        // 校验数据
        checkUser(loginInfo);
        LoginInfo loginInfo2 = loginInfoMapper.cheUserAndType(loginInfo);
        // 根据用户名在数据库中查询对象数据
        if (loginInfo2 == null) {
            throw new CustomException("用户不存在");
        }
        // 比较密码，如果密码不相等，抛出异常  需要用加密的密码来对比
        if (!loginInfo2.getPassword().equals(MD5Utils.encrypByMd5(loginInfo.getPassword()+loginInfo2.getSalt()))) {
            throw new CustomException("密码不正确");
        }

        // 随机产生的token，用于redis的key值
        String token = UUID.randomUUID().toString();
        // 把登录信息放到redis
        redisTemplate.opsForValue().set(token, loginInfo2,30, TimeUnit.MINUTES);

        // 把登录的用户 和 redis中的token放到map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("loginUser", loginInfo2);

        // 通过AjaxResult将map返回给前台
        return AjaxResult.me().setSuccess(true).setResultObject(map);
    }

    /* 验证是否输入了值 */
    private void checkUser(LoginInfo loginInfo) throws CustomException {
        if (StringUtils.isEmpty(loginInfo.getUsername())) {
            throw new CustomException("用户名为空");
        }
        if (StringUtils.isEmpty(loginInfo.getPassword())) {
            throw new CustomException("密码为空");
        }
        if (StringUtils.isEmpty(loginInfo.getType())) {
            throw new CustomException("请完善资料");
        }
    }


}
